<template>
	<u-upload :fileList="files" @afterRead="afterRead" @delete="deleteFile" name="file" :accept="props.accept" multiple
		uploadText="上传完成" :maxCount="props.maxCount"></u-upload>
</template>

<script setup>
	import base from '@/utils/base'
	import {
		ref,
		watch,
	} from 'vue';


	const emit = defineEmits(["updateFiles"])
	const header = ref({
		Authorization: `Bearer ${uni.getStorageSync("token")}`,
		Accept: `application/json`
	})

	const files = ref([])

	let props = defineProps({
		accept: {
			type: String,
			default: "image"
		},
		remoteUrl: {
			type: String,
			default: base.host + "/api/mini/uploadmini"
		},
		maxCount: {
			type: Number,
			default: 1,
		}
	})


	const afterRead = async (event) => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = files.value.length;
		lists.map((item) => {
			files.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			// console.log(result)
			let item = files.value[fileListLen];
			files.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result.url,
			});
			fileListLen++;
		}
		//最后将数据返回
		let resimgs = files.value.map(item => item.url)
		emit("updateFiles", resimgs)
	};

	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				header: header.value,
				url: props.remoteUrl ? props.remoteUrl : base +
				'/api/mini/uploadmini', // 仅为示例，非真实的接口地址
				filePath: url,
				name: 'file',
				formData: {
					user: 'test',
				},
				success: (res) => {
					let result = JSON.parse(res.data)
					resolve(result);
				},
			});
		});
	};

	const deleteFile = (event) => {
		files.value.splice(event.index, 1);
		console.log(files)
		emit("updateFiles", files)
	}
	
	const reset = ()=>{
		console.log("reset被调用============")
		files.value = []
		emit("updateFiles",[])
	}
	//保留reset方法
	defineExpose({
		reset
	})
</script>

<style>

</style>